package com.rongzhe.house.presenter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.rongzhe.house.R;
import com.rongzhe.house.alipay.PayResult;
import com.rongzhe.house.entity.PayContstract;
import com.rongzhe.house.entity.voo.AppoiintmentInfo;
import com.rongzhe.house.entity.voo.OrderVo;
import com.rongzhe.house.internet.DataListener;
import com.rongzhe.house.manager.OrderManager;
import com.rongzhe.house.ui.UiControlInterface;
import com.rongzhe.house.ui.activity.OrderListActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by huang on 2018/1/22.
 */

public class OrderListPresenter extends BasePresenter {
    private static final int SDK_PAY_FLAG = 1;

    public OrderListPresenter(UiControlInterface uiControlInterface) {
        super(uiControlInterface);
    }

    @Override
    public void start(Intent intent) {
        loadData(false);
    }

    public void loadData(final boolean finished) {
        OrderManager.getInstance().getOrderList(finished, new DataListener<List<OrderVo>>() {
            @Override
            public void onSuccess(List<OrderVo> data, String message) {
                if (data != null && data.size() > 0) {
//                    List<OrderVo> filtedData = filterData(finished, data);
                    List<OrderVo> filtedData = data;
                    if (filtedData.size() > 0) {
                        ((OrderListActivity)getUiControlInterface()).visibleEmptyView(false);
                        ((OrderListActivity)getUiControlInterface()).setData(filtedData);
                    } else {
                        ((OrderListActivity)getUiControlInterface()).visibleEmptyView(true);
                    }
                } else {
                    ((OrderListActivity)getUiControlInterface()).visibleEmptyView(true);
                }
            }

            @Override
            public void onFailed(Throwable error, String message) {

            }

            @Override
            public void onEnd() {

            }
        });
    }

    private List<OrderVo> filterData(boolean finishedItem, List<OrderVo> datas) {
        if (datas ==null || datas.size() < 1) {
            return new ArrayList<>();
        }
        List<OrderVo> copyed = new ArrayList<>();
        for (OrderVo data : datas) {
            //过滤已经完成的项
            if (finishedItem) {
                if (data.getStatus() == OrderVo.Companion.getSTATUS_FINISHED()) {
                    copyed.add(data);
                }
            //过滤未完成的项
            } else {
                if (data.getStatus() != OrderVo.Companion.getSTATUS_FINISHED()) {
                    copyed.add(data);
                }
            }
        }
        return copyed;
    }

    public void doStartPay(String orderId) {
        if (TextUtils.isEmpty(orderId)) {
            getUiControlInterface().dismissProgress();
            getUiControlInterface().showToast(getString(R.string.create_order_failed));
        } else {
            OrderManager.getInstance().getAliSign(orderId,
                    new DataListener<PayContstract>() {
                        @Override
                        public void onSuccess(PayContstract data, String message) {
                            getUiControlInterface().dismissProgress();
                            if (data.getCode() == 200) {
                                payV2(data.getData());
                            } else {
                                getUiControlInterface().showToast(
                                        getString(R.string.create_order_failed));
                            }
                        }

                        @Override
                        public void onFailed(Throwable error, String message) {
                            getUiControlInterface().dismissProgress();
                            getUiControlInterface().showToast(message);
                        }

                        @Override
                        public void onEnd() {
                        }
                    });
        }
    }

    /**
     * 支付宝支付业务
     */
    public void payV2(final String data) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask((Activity) getUiControlInterface());
                Map<String, String> result = alipay.payV2(data, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    getUiControlInterface().finish();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        getUiControlInterface().showToast("支付成功");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        getUiControlInterface().showToast("支付失败");
                    }
                    break;
                }
            }
        }
    };
}
